import { CompositeDisposable } from '../event/EventKit';
import { IEventHandler } from './../event/IEventHandler';
import { ViewBase } from './ViewBase';
import { ViewBackState, ViewLayer, ViewMode } from './ViewConsts';
import ViewMgr from './ViewMgr';

export class ViewCtrlBase implements IEventHandler {
    public static viewName: string = null;
    public static viewMode: ViewMode = ViewMode.SINGLE;
    public viewLayer: ViewLayer = ViewLayer.Layer_Normal;
    public viewClass: (typeof ViewBase) = null;
    public viewId: string = null;
    public viewName: string = null;

    private _viewComponent: ViewBase = null

    public arrBeHiddenView: string[];

    /**初始化UI时传入的参数,子类可以重定义参数列表类型 */
    protected params: any = null;

    /**初始化参数 */
    public init(params: any) {
        this.params = params;
    }

    public get viewComponent() { return this._viewComponent }
    public set viewComponent(v: ViewBase) { this._viewComponent = v; }
    disposable: CompositeDisposable;
    disposeEvent(): void {
        this.disposable && this.disposable.dispose();
        this.disposable = null;
    }
    /**注册系统事件 */
    registEvent(): void {
        //子类实现
    }

    /**
     * @desc 检查是否可以使用返回键退出
     * 特殊情况,子类重写方法逻辑,返回ViewBackState.Close则不可以使用返回键关闭
     * @returns ViewBackState
     */
    public checkCanBack(): ViewBackState {
        return ViewBackState.Close;
    }

    /**
     * @desc 检查打开ui时是否可以使用HideOther关闭此页面
     * 默认可以关闭,特殊情况,子类重写方法逻辑,返回false就不会被关
     */
    public checkCanHideByHideOther(): boolean {
        return true;
    }

    public onOpen() {
        this.registEvent();
    }

    public onClose() {
        this.disposeEvent();
        if (this.arrBeHiddenView) {
            ViewMgr.getInstance().activeBeHiddenView(this.arrBeHiddenView);
        }
    }

    private _hideSelf() {
        ViewMgr.getInstance().hideView(this.viewId);
    }

    private _removeSelf() {
        ViewMgr.getInstance().removeView(this.viewId);
    }

    /**
     * @desc 关闭UI
     * @param isRemove 是否使用删除
     * 特殊情况,需要频繁打开的UI,可以传入false,使用隐藏UI的方式关闭
     */
    public close(isRemove: boolean = true) {
        isRemove ? this._removeSelf() : this._hideSelf();
    }

    /**
     * 所有对视图组件的操作都通过此方法进行操作，不可直接调用viewComponent
     * @param method 视图组件的方法名
     * @param arg 参数
     */
    protected viewDoAction(method: string, ...arg: any[]) {
        if (!this._viewComponent) {
            return
        }

        if (this._viewComponent[method]) {
            this._viewComponent[method].apply(this._viewComponent, arg)
        }
    }

}
